package com.founder.android.parser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.founder.android.data.GeoData;

public class GeocodeJSONParser {
	
	public static String getUrl(double lat, double lng) {
		return String.format(
				"http://maps.google.cn/maps/api/geocode/json?latlng=%.6f,%.6f&sensor=true&language=zh-CN", 
				lat, lng);
	}
	
	public static String formatCity(String city) {
		city = city.replace("中国", "");
		city = city.replace("省", " ");
		return city;
	}

	public static GeoData parser(String json) throws JSONException {
		JSONObject obj = new JSONObject(json);
		JSONArray results = obj.getJSONArray("results");
		JSONObject result;
		for (int i = 0; i < results.length(); i++) {
			result = results.getJSONObject(i);
			JSONArray types = result.getJSONArray("types");
			if (containsLocality(types)) {
				String address = result.getString("formatted_address");
				JSONObject geometry = result.getJSONObject("geometry");
				JSONObject location = geometry.getJSONObject("location");
				String lat = location.getString("lat");
				String lng = location.getString("lng");
				return new GeoData(address, lat, lng);
			}
		}
		return null;
	}
	
	private static boolean containsLocality(JSONArray types) throws JSONException {
		for (int i = 0; i < types.length(); i++) {
			String type = types.getString(i);
			if ("locality".equals(type)) {
				return true;
			}
		}
		return false;
	}

}
